package com.baosight.risk.webservice;

import lombok.extern.slf4j.Slf4j;
import org.apache.axis.client.Call;
import org.apache.axis.client.Service;
import org.apache.axis.encoding.ser.BeanDeserializerFactory;
import org.apache.axis.encoding.ser.BeanSerializerFactory;
import javax.xml.namespace.QName;
import java.rmi.RemoteException;

@Slf4j
public class WsCall {

    private String wsUrl;
    private String operateName;
    private boolean initFlag = false;
    private Call call = null;

    public WsCall(String wsUrl, String operateName) {
        this.wsUrl = wsUrl;
        this.operateName = operateName;
    }

    public void init() {
        if (!this.initFlag) {
            try {
                Service service = new Service();
                this.call = (Call) service.createCall();
                //设置地址
                this.call.setTargetEndpointAddress(this.wsUrl);
                //设置要执行的方法
                this.call.setOperationName(this.operateName);
                this.initFlag = true;
            } catch (Exception e) {
                log.error(e.getMessage());
            }
        }
    }

    public Object invokeOperate(Object[] params) throws Exception {
        Object result = null;
        if (this.initFlag) {
            try {
                result = this.call.invoke(params);
            } catch (RemoteException e) {
                log.error(e.getMessage());
            }
        } else {
            throw new Exception("webservice客户端未初始化");
        }
        return result;
    }

    /**
     * @description 调用远程方法，使用复杂对象作为参数
     * @author lishaoqing
     * @date 2020/5/18
     */
    public Object invokeByNamespace(String namespace, String complexType, Object request, Object response, Object[] params) throws Exception {
        Object result = null;
        if (this.initFlag) {
            try {
                //接口的命名空间
                QName qn = new QName(namespace, complexType);
                call.registerTypeMapping(
                        request.getClass(),
                        qn,
                        new BeanSerializerFactory(request.getClass(), qn),
                        new BeanDeserializerFactory(request.getClass(), qn));
//                call.setReturnClass(response);
                result = this.call.invoke(params);
            } catch (RemoteException e) {
                log.error(e.getMessage());
            }
        } else {
            throw new Exception("webservice客户端未初始化");
        }
        return result;
    }

    public String getWsUrl() {
        return wsUrl;
    }

    public String getOperateName() {
        return operateName;
    }

}